<template>
  <div>
    <Modal
      v-model:visible="showContract"
      :title="announcementId ? '修改公告' : '新增公告'"
      @ok="onSubmit"
    >
      <Form
        class="form_box"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
      >
        <FormItem label="标题" name="title">
          <Input v-model:value="formState.title" placeholder="请输入标题" />
        </FormItem>
        <FormItem label="公告内容" name="content">
          <a-textarea v-model:value="formState.content" placeholder="请输入公告内容" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, getCurrentInstance } from 'vue';
  import { Modal, Form, Input, FormItem, message } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { noticeModifyApi, noticeCreateApi } from '/@/api/announcements';
  const instance = getCurrentInstance();

  const { createMessage } = useMessage();
  const emit = defineEmits(['reload']);
  const formRef = ref();
  const formState = reactive({
    title: '',
    content: '',
  });

  const rules = {
    title: [{ required: true, message: '请输入标题' }],
    content: [{ required: true, message: '请输入公告内容' }],
  };

  const showContract = ref(false);
  const announcementId = ref(null);
  const init = (data) => {
    resetForm();
    announcementId.value = null;
    if (data?.id) {
      announcementId.value = data.id;
      formState.title = data.title;
      formState.content = data.content;
    }
    showContract.value = true;
  };
  const onSubmit = () => {
    formRef.value
      .validate()
      .then(() => {
        if (announcementId.value) {
          noticeModifyApi({
            id: announcementId.value,
            ...formState,
          }).then((res) => {
            if (res != false) {
              message.success('修改成功');
              showContract.value = false;
              resetForm();
              emit('reload');
            }
          });
        } else {
          noticeCreateApi(formState).then((res) => {
            console.log(res, 'res');
            if (res != false) {
              message.success('新增成功');
              showContract.value = false;
              resetForm();
              emit('reload');
            }
          });
        }
      })
      .catch((error: any) => {
        console.log('error', error);
      });
  };
  const resetForm = () => {
    formState.title = '';
    formState.content = '';
  };

  defineExpose({
    init,
  });
</script>
<style>
  .form_box {
    padding: 20px;
  }
</style>
